/**
 * 表单设计 编辑页
 *
 * 作者 fenghaijun
 * 日期 2024-08-28 10:54:00
 */
layui.use(['jquery','febs', 'form', 'validate', 'formDesigner','commonJS','staticField'], function () {
    var $ = layui.$,
        febs = layui.febs,
        layer = layui.layer,
        form = layui.form,
        commonJS = layui.commonJS,
        staticField = layui.staticField,
        $view = $('#formDesign-edit'),
        validate = layui.validate,
        formDesigner = layui.formDesigner;
    var tenantId = POPUP_DATA.tenantId
    // 加载模板
    getAllTemplate()
    function getAllTemplate(){
        febs.get(ctx + 'formDesign?templateFlg=1&tenantId=' + tenantId, null, function (res) {
          if(res.data && res.data.length > 0){
              staticField.templateFormList=[]
              $('#template-form-list').empty()
              res.data.forEach(item =>{
                  staticField.templateFormList.push({
                      text: item.formName,
                      imageUrl: "../formDesigner/images/1.PNG",
                      value:JSON.parse(item.formHtml)
                  })
              })
          }
          initFormValue();
        })
    }



    var   render

    form.verify(validate);
    form.render();
    var selectDeptList = [],selectUserList = []
    function initFormValue() {
        if(!commonJS.isEmpty(formDesignData)){
            // 编辑
            let formData = JSON.parse(formDesignData.formHtml)
            render = formDesigner.render({
                data:formData,
                elem:'#formDesigner'
            });
            // 适用部门/人赋值
            if(formDesignData.publishObject == "2"){
                selectDeptList = formDesignData.deptList
                $('.selectedCommonBox').empty()
                selectDeptList.forEach((item, index) => {
                    $('.selectedCommonBox').append('<span class="tag" style="height: 30px;margin-bottom:10px;background-color:#ECF5FF;box-sizing:border-box;color: #409EFF;display: flex;align-items: center;padding: 10px;margin-right: 12px;">'+ item.deptName +'<span style="color: red;margin-left: 5px;cursor:pointer;" data-index="'+ index +'" data-type="3" onclick="delTags(this)">x</span></span>')
                })
            }else if(formDesignData.publishObject == "3"){
                selectUserList = formDesignData.userList
                $('.selectedCommonBox').empty()
                selectUserList.forEach((item, index) => {
                    $('.selectedCommonBox').append('<span class="tag" style="height: 30px;margin-bottom:10px;background-color:#ECF5FF;box-sizing:border-box;color: #409EFF;display: flex;align-items: center;padding: 10px;margin-right: 12px;">'+ item.uname +'<span style="color: red;margin-left: 5px;cursor:pointer;" data-index="'+ index +'" data-type="3" onclick="delTags(this)">x</span></span>')
                })
            }
            if(formDesignData.templateFlg == "1"){
                $("input[name=templateFlg]").prop('checked',true)
            }else{
                $("input[name=templateFlg]").prop('checked',false)
            }
            $('#publishObject').val(formDesignData.publishObject)
            if(formDesignData.publishObject == '2'){
                // 部门
                $('#objectLabel').html('<span style="color:red;">*</span>适用部门：')
                $("input[name='objectId']").attr('placeholder','请选择适用部门')
                $('#selectObject').removeClass('layui-hide')
                $('#selectPerson').addClass('layui-hide')
                $('#selectDept').removeClass('layui-hide')
                let selectedNames = formDesignData.deptList.map(item=>item.deptName)
                $("input[name='objectId']").val(selectedNames)
            }else if(formDesignData.publishObject == '3'){
                // 个人
                $('#objectLabel').html('<span style="color:red;">*</span>适用人：')
                $("input[name='objectId']").attr('placeholder','请选择适用人')
                $('#selectObject').removeClass('layui-hide')
                $('#selectDept').addClass('layui-hide')
                $('#selectPerson').removeClass('layui-hide')
                let selectedNames = formDesignData.userList.map(item=>item.uname)
                $("input[name='objectId']").val(selectedNames)
            }

            form.val("formDesign-edit-form", {
                "designId": formDesignData.designId,
                "tenantId": formDesignData.tenantId,
                "formName": formDesignData.formName,
                "startDate": formDesignData.startDate,
                "endDate": formDesignData.endDate,
                "version": formDesignData.version,
                "status": formDesignData.status,
            });
            // 表单赋值

        }else{
            render =formDesigner.render({
                data:[],
                elem:'#formDesigner'
            });
        }
    }

    form.on('submit(formDesign-edit-form-submit)', function (data) {
        febs.modal.open('表单预览', 'formPreview', {
            area: ['95%','95%'],
            btn: ['关闭'], //可以无限个按钮
            yes: function (index, layero) {

                layer.close(index);
            },
            data:render.getOptions().data,
            allDone: function () {


            }
        });
        // addOrUpdate(data.field);
        return false;
    });

    $view.find('#selectPersonEdit').on('click',function(){
        febs.modal.open('选择适用人', 'common/user', {
            btn: ['确认','关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
            data:{
                tenantId:tenantId,
                multiple:true,
            },
            yes: function (index, layero) {
                let selectData = null
                if(typeof getSelectData  === 'function'){
                    selectData = getSelectData()
                }

                if(selectData && selectData.length>0){
                    selectUserList = selectData
                    $('.selectedCommonBox').empty()
                    selectData.forEach((item, index) => {
                        $('.selectedCommonBox').append('<span class="tag" style="height: 30px;margin-bottom:10px;background-color:#ECF5FF;box-sizing:border-box;color: #409EFF;display: flex;align-items: center;padding: 10px;margin-right: 12px;">'+ item.uname +'<span style="color: red;margin-left: 5px;cursor:pointer;" data-index="'+ index +'" data-type="3" onclick="delTags(this)">x</span></span>')
                    })
                }
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });
    })
    $view.find('#selectDeptEdit').on('click',function(){
        febs.modal.open('选择适用部门', '/common/dept', {
            btn: ['提交','取消'],
            area: ['500px','800px'],
            data: {
                tenantId: tenantId,
                multiple:true,
            },
            yes: function (index, layero) {
                let deptData = null
                if(typeof getSelectData == "function"){
                    deptData = getSelectData()
                }
                if(deptData){
                    selectDeptList = deptData
                    $('.selectedCommonBox').empty()

                    deptData.forEach((item, index) => {
                        $('.selectedCommonBox').append('<span class="tag" style="height: 30px;margin-bottom:10px;background-color:#ECF5FF;box-sizing:border-box;color: #409EFF;display: flex;align-items: center;padding: 10px;margin-right: 12px;">'+ item.deptName +'<span style="color: red;margin-left: 5px;cursor:pointer;" data-index="'+ index +'" data-type="2" onclick="delTags(this)">x</span></span>')
                    })

                }
                layer.close(index);
                return false;
            },
            btn2: function (index) {
                layer.close(index);
            },
        });
    })
    window.delTags = function (event){
        let index = $(event).attr('data-index')
        let type = $(event).attr('data-type')

        if(type == 2){
           selectDeptList.splice(index,1)
        }else{
            selectUserList.splice(index,1)
        }
        $(event).parent().remove()
    }
    $view.find('#save').on('click',function (){
        let designId = $view.find('input[name=designId]').val() || ''
        let formName = $view.find('input[name=formName]').val()
        let startDate = $view.find('input[name=startDate]').val()
        let endDate = $view.find('input[name=endDate]').val()
        let version =$view.find('input[name=version]').val()
        let templateFlg = $view.find('input[name=templateFlg]').val()
        let formHtml = render.getOptions().data

        if(commonJS.isEmpty(formName)){
            febs.alert.warn('请输入表单名称');
            return false
        }

        if(commonJS.isEmpty(startDate)){
            febs.alert.warn('请输入开始时间');
            return false
        }
        // 适用范围
        let publishObject = $('#publishObject').find("option:selected").val()

        let length = $('.selectedCommonBox').find('.tag').length
        if(publishObject == '2'){
            // 适用部门必填
            if(length == 0){
                febs.alert.warn('请选择适用部门');
                return false
            }
        }
        if(publishObject == '3'){
            // 适用人必填
            if(length == 0){
                febs.alert.warn('请选择适用用户');
                return false
            }
        }
        if(formHtml.length==0){
            febs.alert.warn('请设计表单');
            return false
        }

        let obj = {
            tenantId:tenantId,
            formName:formName,
            startDate:startDate,
            endDate:endDate,
            version:version,
            formHtml:JSON.stringify(formHtml),
            status:1,
            designId:designId,
            templateFlg:templateFlg,
            publishObject:publishObject
        }
        if(formDesignData){
            obj.formPublishObjectList = formDesignData.formPublishObjectList ? formDesignData.formPublishObjectList : []
        }
        if(publishObject == '2'){
            obj.deptList = selectDeptList
        }else if(publishObject == '3'){
            obj.userList = selectUserList
        }
        addOrUpdate(obj);
        return false;
    })

    function addOrUpdate(data) {
        febs.modal.confirm("保存提示","是否保存表单信息？",function (index){
            if (data.designId && data.designId.length > 0) {
                febs.postArray(ctx + 'formDesign/update', data, function () {
                    layer.closeAll();
                    febs.alert.success('修改成功');
                    $('#febs-formDesign').find('#query').trigger('click');
                });
            } else {
                febs.postArray(ctx + 'formDesign', data, function () {
                    layer.closeAll();
                    febs.alert.success('新增成功');
                    $('#febs-formDesign').find('#query').trigger('click');
                });
            }
        })

    }
});